Skip to content

Conversation

deeringc
Copy link
Contributor

@deeringc deeringc commented Oct 1, 2017

In our code base we have a repeating pattern of accessing json objects while interpreting server responses.

It looks something like as follows:

if(val.has_field(U("key")) && val.at(U("key")).is_string()) { something = val.at(U("key")).as_string() }

Both of these checks are required or a json exception will be thrown at runtime. This is quite verbose and problematic as sometimes developers on our team forget to check both of these. I'm proposing adding a new check for each type supported in json that combines these two checks into one.

With this change the above code becomes:
if(val.has_string_field(U("key"))) { something = val.at(U("key")).as_string() }

Adding unit tests for has_<type>_field utilities
@ras0219-msft
Copy link
Contributor

These seem quite reasonable to me as is, though they leave a bit of performance on the table (in the pattern you have, it makes 3 separate lookups).

I think to fix this would really require std::optional, however, so I think these APIs could live alongside some future .maybe_get_string_field() just fine.

@ras0219-msft ras0219-msft merged commit ec1119d into microsoft:master Oct 2, 2017
@deeringc
Copy link
Contributor Author

deeringc commented Oct 2, 2017

Agreed, once CppRestSDK uses c++17 then std::optional is the way to go! Actually, I can make this more efficient so that it does one less lookup. I'll follow up with another PR. Thanks for the feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants